//
//  UITextView+Placeholder.m
//  UITextView
//
//  Created by 陈亚勃 on 16/1/11.
//  Copyright © 2016年 cyb. All rights reserved.
//

#import "UITextView+Placeholder.h"
#import <objc/runtime.h>
static NSString * kPlaceholder;
static NSString * kPlaceholderColor;
static NSString * kTempColor;
static NSString * kIsPlaceholder;
@interface UITextView()
@property (nonatomic, strong)UIColor *tempColor;
/**
 *  判断是否是placeholder
 */
@property (nonatomic, assign)BOOL isPlaceholder;
@end

@implementation UITextView (Placeholder)

- (void)setPlaceholder:(NSString *)placeholder{
    objc_setAssociatedObject(self, &kPlaceholder, placeholder, OBJC_ASSOCIATION_COPY_NONATOMIC);
    if (self.text.length > 0 || self.isPlaceholder == NO) {
        return;
    }
    self.tempColor = self.textColor;
    self.text = self.placeholder;
    self.textColor = self.placeholderColor;
    self.isPlaceholder = placeholder.length > 0 ? YES:NO;
}

- (NSString *)placeholder{
    return objc_getAssociatedObject(self, &kPlaceholder);
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    objc_setAssociatedObject(self, &kPlaceholderColor, placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIColor *)placeholderColor{
    return objc_getAssociatedObject(self, &kPlaceholderColor);
}

- (void)setTempColor:(UIColor *)tempColor{
    objc_setAssociatedObject(self, &kTempColor, tempColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIColor *)tempColor{
    return objc_getAssociatedObject(self, &kTempColor);
}

- (void)setIsPlaceholder:(BOOL)isPlaceholder{
    NSNumber *isPlaceBool = [NSNumber numberWithBool:isPlaceholder];
    objc_setAssociatedObject(self, &kIsPlaceholder, isPlaceBool, OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)isPlaceholder{
    return [objc_getAssociatedObject(self, &kIsPlaceholder) boolValue];
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEdit:) name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEdit:) name:UITextViewTextDidEndEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)beginEdit:(NSNotification *)info{
    self.text = self.isPlaceholder? @"":self.text;
    self.textColor = self.tempColor;
}

- (void)endEdit:(NSNotification *)info{
    if (self.text.length == 0) {
        self.text = self.placeholder;
        self.tempColor = self.textColor;
        self.textColor = self.placeholderColor;
        self.isPlaceholder = YES;
    }else{
        self.isPlaceholder = NO;
    }
}

- (void)changeText:(NSNotification *)info{
    
}

@end
